﻿#region HeaderComments
// ***********************************************************************************************************************************************
// Copyright (C) # YEAR # # York #
// 作    者：# CaiTao #
// 创建日期：# CREATIONDATE #
// 功能描述：# Json文件的获取 #
// 修改记录：# MODIFICATIONRECORD #
// ***********************************************************************************************************************************************
#endregion

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
using System.Linq;

namespace York.JSONConfig
{
    public class ConfigSetting
    {
        private static ConfigSetting instance;
        public static ConfigSetting Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ConfigSetting(Dirpath);
                }
                return instance;
            }
        }

        private static string Dirpath = Application.streamingAssetsPath + @"\JSONConfig";
        private Newtonsoft.Json.Linq.JToken _config;

        public ConfigSetting(string path)
        {
            _config = new Newtonsoft.Json.Linq.JObject();

            LoadConfig();
            //new System.Threading.Thread(LoadConfig).Start();
        }

        /// <summary>
        /// 加载配置文件
        /// </summary>
        private void LoadConfig()
        {
            string[] fs = System.IO.Directory.GetFiles(Dirpath, "*.json", System.IO.SearchOption.AllDirectories);
            for (int i = 0; i < fs.Length; i++)
            {
                try
                {
                    _config[FileName(fs[i])] = (Newtonsoft.Json.Linq.JToken)JsonConvert.DeserializeObject(System.IO.File.ReadAllText(fs[i]));
                }
                catch
                {
                    Debug.LogError(fs[i] + "解析失败");
                }
            }
        }

        /// <summary>
        /// 根据配置文件路径获取文件名
        /// </summary>
        /// <param name="fullpath"></param>
        /// <returns></returns>
        private string FileName(string fullpath)
        {
            int index = fullpath.LastIndexOf("\\");
            string tempName = fullpath.Substring(index + 1, fullpath.Length - index - 1);
            index = tempName.LastIndexOf(".");
            return tempName.Substring(0, index);
        }

        /// <summary>
        /// 根据文件名获取文件全路径
        /// </summary>
        /// <param name="configFileName"></param>
        /// <returns></returns>
        public string GetConfigFile(string configFileName)
        {
            string[] fs = Directory.GetFiles(Dirpath, "*.json", SearchOption.AllDirectories);

            string filePath = fs.FirstOrDefault((file) =>
            {
                string fileName = FileName(file);
                if (fileName == configFileName)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            
            return filePath;
        }

        public string GetConfigFile(string dir,string configFileName)
        {
            string[] fs = Directory.GetFiles(Dirpath + "/" + dir, "*.json", SearchOption.TopDirectoryOnly);

            string filePath = fs.FirstOrDefault((file) =>
            {
                string fileName = FileName(file);
                if (fileName == configFileName)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });

            return filePath;
        }

        public string[] GetConfigFiles(string dir)
        {
            string[] fs = Directory.GetFiles(Dirpath + "/" + dir, "*.json", SearchOption.TopDirectoryOnly);

            return fs;
        }

        public string CreateConfigFile(string configFileName)
        {
            string filePath = Path.Combine(Dirpath, configFileName + ".json");
            FileInfo file = new FileInfo(filePath);
            //创建文件  
            FileStream fileStream = file.Create();

            //关闭文件流
            fileStream.Close();

            return filePath;
        }

        public string CreateConfigFile(string dir, string configFileName)
        {
            string filePath = Path.Combine(Dirpath, dir, configFileName + ".json");
            FileInfo file = new FileInfo(filePath);
            //创建文件  
            FileStream fileStream = file.Create();

            //关闭文件流
            fileStream.Close();
            return filePath;
        }

        /// <summary>
        /// 索引器
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Newtonsoft.Json.Linq.JToken this[string key]
        {
            get
            {
                return _config[key] as Newtonsoft.Json.Linq.JToken;
            }
        }
    }
}

